package org.baitu.zzim.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangkai_a
 * @date 2025/7/9 10:11
 */

@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${server.port:8080}")
    private int serverPort;

    private String getCurrentNodeAddress() {
        try {
            return InetAddress.getLocalHost().getHostAddress() + ":" + serverPort;
        } catch (UnknownHostException e) {
            throw new RuntimeException("无法获取本地主机地址", e);
        }
    }

    // 用户连接节点存储相关方法
    public void saveUserNode(String userId) {
        String nodeAddress = getCurrentNodeAddress();
        redisTemplate.opsForValue().set("user_node:user" + userId, nodeAddress);
    }

    public String getUserNode(String userId) {
        return (String) redisTemplate.opsForValue().get("user_node:user" + userId);
    }

    public void removeUserNode(String userId) {
        redisTemplate.delete("user_node:user" + userId);
    }

    // 通用方法
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean set(String key, Object value, long timeout, TimeUnit unit) {
        try {
            redisTemplate.opsForValue().set(key, value, timeout, unit);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    public boolean delete(String key) {
        return Boolean.TRUE.equals(redisTemplate.delete(key));
    }
}